/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_console.htm
 *
 * Zhiqim Console is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager;

import java.util.Collection;
import java.util.List;
import java.util.TreeMap;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.ZmlBootstrap;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.logging.Logs;
import org.zhiqim.kernel.model.codes.Base64;
import org.zhiqim.kernel.util.Bytes;
import org.zhiqim.kernel.util.Files;
import org.zhiqim.kernel.util.Randoms;
import org.zhiqim.kernel.util.Resources;
import org.zhiqim.kernel.util.Streams;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.dbo.ZmrAvatar;
import org.zhiqim.manager.dbo.ZmrOperator;

/**
 * 初始化引导类
 *
 * @version v1.0.0 @author zouzhigang 2015-5-28 新建与整理
 */
@AnAlias("ZmrBootstrap")
public class ZmrBootstrap extends ZmlBootstrap implements ZmrConstants
{
    private static ZmrPassworder passworder = new ZmrPassworder();
    private static TreeMap<Long, ZmrAvatar> aMap = new TreeMap<>();
    
    /*******************************************************************************/
    //初始化
    /*******************************************************************************/
    
    @Override
    public void log(HttpRequest request, String message, Throwable e)
    {
        if (message != null && Strings.contains(message, "[sessionUser]"))
            return;//sessionUser类的调用不打日志
        
        super.log(request, message, e);
    }
    
    @Override
    protected void initBefore() throws Exception
    {
        context.setAttribute(ZmrBootstrap.class, this);
    }
    
    @Override
    protected void initAfter() throws Exception
    {
        initAvatar();
        getOperator();
    }
    
    /** 初始化头像 */
    private void initAvatar() throws Exception
    {
        long avatarId = ID13, avatarTime = System.currentTimeMillis();
        List<String> avatarNameList = Resources.getResourceNameList(ZmrBootstrap.class, AVATAR_PREFIX);
        for (String avatarName : avatarNameList)
        {
            byte[] data = Streams.getBytesClassPath(ZmrBootstrap.class, AVATAR_PREFIX + avatarName);
            
            data = Bytes.resizePNG(data, 100, 100);
            
            ZmrAvatar avatar = new ZmrAvatar();
            avatar.setAvatarId(avatarId);
            avatar.setAvatarTime(avatarTime);
            avatar.setAvatarData(data);
            
            aMap.put(avatarId++, avatar);
        }
    }
    
    /*******************************************************************************/
    //获取静态初始化数据
    /*******************************************************************************/
    
    public static ZmrPassworder getPassworder()
    {
        return passworder;
    }
    
    public static ZmrAvatar getAvatar(long avatarId)
    {
        return aMap.get(avatarId);
    }
    
    public static Collection<ZmrAvatar> getAvatarList()
    {
        return aMap.values();
    }
    
    public static String getPrivateKey()
    {
        return ZMR_CONSOLE_PRIVATE;
    }
    
    public static String getPublicKey()
    {
        return ZMR_CONSOLE_PUBLIC;
    }
    
    /*******************************************************************************/
    //操作员数据
    /*******************************************************************************/
    
    public static ZmrOperator getOperator()
    {
        String value = Files.readUTF8(ZMR_CONSOLE);
        if (Validates.isEmptyBlank(value))
        {
            //随机盐值
            String passSalt = Randoms.lettersDigitsSecure(64);
            
            ZmrOperator operator = new ZmrOperator();
            operator.setOperatorCode(Z_NAME);
            operator.setOperatorPass(passworder.encode(Z_NAME, ZMR_PASSWORD, passSalt));
            operator.setOperatorPassSalt(passSalt);
            operator.setOperatorAvatar(ID13);
            operator.setRememberCode(true);
            
            //保存到文件
            saveOperator(operator);
            return operator;
        }
        
        value = Base64.decodeUTF8(value);
        return Jsons.toObject(value, ZmrOperator.class);
    }
    
    public static void saveOperator(ZmrOperator operator)
    {
        String value = Base64.encodeUTF8(Jsons.toString(operator));

        try
        {//持久化到配置文件
            Files.writeUTF8(ZMR_CONSOLE, value);
        }
        catch (Exception e)
        {
            Logs.error("保存操作员配置信息异常", e);
        }
    }
}
